package api

import (
	"cap/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
	"lib/http"
	"lib/structs/cap"
	http2 "net/http"
)

var SessionApi = new(sessionApi)

type sessionApi struct {
}

func (a sessionApi) Conn(c *gin.Context) {
	var in cap.OpenLinkDto
	if err := c.ShouldBindQuery(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	var UpGrader = websocket.Upgrader{
		CheckOrigin: func(r *http2.Request) bool {
			return true
		},
		// 在原始websocket中添加对guacamole协议的支持
		Subprotocols: []string{"guacamole"},
	}
	ws, err := UpGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	err = service.SessionSer.Conn(in, ws)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
}

func (a sessionApi) BindWinSessionId(c *gin.Context) {
	in := struct {
		SessionId    int64 `json:"sessionId,string"`
		WinSessionId int   `json:"winSessionId,string"`
	}{}
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	err := service.SessionSer.BindWinSessionId(in.SessionId, in.WinSessionId)
	if err != nil {
		logrus.Errorf("BindWinSessionId err: %v", err)
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}

func (a sessionApi) InsertOpenAppLogs(c *gin.Context) {
	in := struct {
		LinkId       int64 `json:"linkId,string"`
		SessionId    int64 `json:"sessionId,string"`
		WinSessionId int   `json:"winSessionId"`
	}{}
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	err := service.SessionSer.InsertOpenAppLogs(in.LinkId, in.SessionId, in.WinSessionId)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.OK204(c)
}
func (a sessionApi) GetCapAppInfo(c *gin.Context) {
	in := struct {
		LinkId    int64 `json:"linkId,string"`
		SessionId int64 `json:"sessionId,string"`
	}{}
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	vmApp, err := service.SessionSer.GetCapAppInfo(in.LinkId, in.SessionId)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.Ok(c, vmApp)
}

func (a sessionApi) Create(c *gin.Context) {
	var in cap.AddSessionForm
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	me := http.GetCurrentUser(c)
	id, err := service.SessionSer.Create(in.LinkId, *me)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.Ok(c, fmt.Sprintf("%d", id))
}

func (a sessionApi) Page(c *gin.Context) {
	var in cap.SearchSessionForm
	if err := c.ShouldBindQuery(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	li, total, err := service.SessionSer.Page(in)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.OkPage(c, li, total)
}
